package com.controller.lib.upgrade

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.text.TextUtils
import com.controller.lib.utils.FileUtils.Companion.deleteFile
import timber.log.Timber

/**
 * author : gerui
 * date   : 2021/11/4 16:49
 * desc   : 静默安装APK事件通知
 * version: 1.0
 */
class ApkInstallReceive : BroadcastReceiver() {
  override fun onReceive(context: Context, intent: Intent) {
    val extras = intent.extras
    Timber.i("onReceive_%s", extras)
    if (extras != null) {
      val action = intent.action
      val data = intent.dataString
      val status = extras.getInt(PackageInstaller.EXTRA_STATUS)
      Timber.i("action:%s  status:%s data_%s", action, status, data)
      if (TextUtils.equals(PACKAGE_INSTALLED_ACTION, intent.action)) {
        val message = extras.getString(PackageInstaller.EXTRA_STATUS_MESSAGE)
        when (status) {
          PackageInstaller.STATUS_SUCCESS -> Timber.i("install success")
          PackageInstaller.STATUS_FAILURE, PackageInstaller.STATUS_FAILURE_ABORTED, PackageInstaller.STATUS_FAILURE_BLOCKED, PackageInstaller.STATUS_FAILURE_CONFLICT, PackageInstaller.STATUS_FAILURE_INCOMPATIBLE, PackageInstaller.STATUS_FAILURE_INVALID, PackageInstaller.STATUS_FAILURE_STORAGE -> Timber.w(
            "Install failed! status:%s, message:%s",
            status,
            message
          )
          else -> Timber.w("Unrecognized status received from installer: _%s", status)
        }
        deleteFile(data)
      }
      InstallHelper.restartApp(context, 200)
    }
  }

  companion object {
    /**
     * 静默安装广播
     */
    const val PACKAGE_INSTALLED_ACTION: String =
      "com.android.packageinstaller.ACTION_INSTALL_COMMIT"
  }
}
